﻿<%@ Page Title="" Language="C#" MasterPageFile="~/controlasistencia/Plantilla.Master" AutoEventWireup="true" CodeBehind="Horario.aspx.cs" Inherits="Presentacion.Horario" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="js/plugins/jstz/jstz-1.0.4.min.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contenido" runat="server">
    <div class="row">
        <div class="col-lg-12">
            <div class="page-title">
                <h1><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h1> 
                <ol class="breadcrumb">
                    <li><i class="fa"></i><a href="index.aspx" class="tamano-breadcrumbs">Inicio</a>
                    </li>
                    <li class="active tamano-breadcrumbs">HORARIO ACADÉMICO</li>
                </ol>
            </div>
        </div>
        <!-- /.col-lg-12 -->
    </div>
    <!-- /.row -->
    <div class="col-md-9">
        <div class="portlet portlet-default">
            <div class="box-body no-padding">
                <!-- THE CALENDAR -->
                <form id="form1" runat="server">
                    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
                    </asp:ScriptManager>
                    <div class="clearfix"></div>
                    <div class="portlet-body">
                        <h3 class="text-green" style="text-align: center"><b>HORARIO DE CLASES</b></h3>
                        <div id="calendar"></div>
                    </div>
                    <!-- /.portlet -->
                </form>

                <%--</br>
                                    <center><button class="btn btn-green">Confirmar</button></center>--%>
            </div>
            <!-- /.box-body -->
        </div>
        <!-- /. box -->
    </div>
    <!-- /.col -->



    <div class="col-lg-3">
        <div class="portlet portlet-green">
            <div class="portlet-heading">
                <div class="portlet-title">
                    <h4>Programador de materias</h4>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="portlet-body">
                <!-- the events -->
                <div id="eventos" runat="server">
                </div>
            </div>
            <!-- /.box-body -->
        </div>
        <!-- /. box -->

    </div>
    <!-- /.col -->

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="script" runat="server">

    <!-- Funciones para lanzar los mensajes de eventos -->
    <script src="js/notifications.js"></script>
    <script>
        //$(document).ready(function  () {
        //        $('#CASYS').fullCalendar('removeEvents','refetchEvents');
        //});                                                   
        
        function showModal() {
            $(document).ready(function () {
                var timezone = jstz.determine();
                var n = timezone.name();
                if (n != 'America/Bogota') {
                    alert('Para continuar con el ingreso del horario de clases, por favor corrija la zona horaria del computador (Bogota, Quito, Lima)');
                    window.history.back();
                }
                else {
                    
                }
            });
        }
        window.onload = showModal();

        function rgb2hex(rgb) {
            rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            return "#" +
             ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
             ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
             ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2);
        }
        $(function () {

            /* initialize the external events
             -----------------------------------------------------------------*/
            function ini_events(ele) {
                ele.each(function () {

                    // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
                    // it doesn't need to have a start or end
                    var eventObject = {
                        
                        title: $.trim($(this).text()) // use the element's text as the event title
                    };

                    // store the Event Object in the DOM element so we can get to it later
                    $(this).data('eventObject', eventObject);

                    // make the event draggable using jQuery UI
                    $(this).draggable({
                        zIndex: 1070,
                        revert: true, // will cause the event to go back to its
                        revertDuration: 0  //  original position after the drag
                    });

                });
            }
            ini_events($('#external-events div.external-event'));

            /* initialize the calendar
             -----------------------------------------------------------------*/
            //Date for the calendar events (dummy data)
            
            var date = new Date();
            var d = date.getDate(),
                m = date.getMonth(),
                y = date.getFullYear();
            $('#calendar').fullCalendar({
                defaultView: 'agendaWeek',
                left: 'prev,next today',
                weekends: false,                   
               
                allDaySlot: false,
                <%
        Negocio.catalogos.catalogoCarrera _objCatalogoCarrera = new Negocio.catalogos.catalogoCarrera();
        var codigoCarrera = new Presentacion.encriptaje().decodeControlAsistencia(Request.QueryString["ca"].ToString());
        if (_objCatalogoCarrera.obtenerCarreraxID(int.Parse(codigoCarrera)).First().seccion == "DIURNA")
        {
            Response.Write(
                "slotMinutes: 30,"+
                "slotLabelInterval: '00:30:00'," +
                "minTime: '7'," +
                "maxTime:'19',");
        }
        else
        {
            Response.Write(
                 "slotMinutes: 15," +
                 "slotLabelInterval: '00:15:00',"+
                "minTime: '17'," +
                "maxTime:'22:15',");
            
        }
                 %>
                defaultEventMinutes : 60,

                header: {
                    left:false,
                    right: 'agendaWeek,agendaDay',
                    center: false,
                },
                columnFormat: {
                    month: 'ddd',
                    week: 'ddd',
                    day: 'dddd'
                },
                axisFormat: 'H:mm', //,'h(:mm)tt',
                timeFormat: {
                    agenda: 'H:mm' //h:mm{ - h:mm}'
                },
                
                buttonText: {//This is to add icons to the visible buttons
                    week: 'Semana',
                    day: 'Hoy'
                },
                events: <% Response.Write(controlasistencia_horario_aspx.obtenerHorario(int.Parse(Session["idDocente"].ToString()), int.Parse(Session["periodo"].ToString()), Request.QueryString["ca"].ToString())); %>,
                <%    
        var inicioDeClases = new Negocio.catalogoCalendarioAcademico().obtenerInicioANDFinDeClases(int.Parse(Session["periodo"].ToString()), "#00a65a");
        if (inicioDeClases != null )
        {
            if (inicioDeClases.start.Value.Month == DateTime.Now.Month)
            {
                
           %>
                editable: true,
                selectable: false,
                eventResize: function (event, dayDelta, minuteDelta, revertFunc)   {

                    var nDifference = Math.abs(new Date(event.start) - new Date( event.end));
                    var one_day = 1000*60;
                    if (event.id == 'CASYS') {
                        revertFunc();
                    }
                    else {
                        if ((Math.round(nDifference/one_day)% 60) == 0 ) {  
                    
                            var idPeriodo = <% Response.Write(Session["periodo"].ToString()); %>;
                            var idDistribucion = "<% Response.Write(Session["idDocente"].ToString()); %>";

                            var eventToUpdate = {
                                idDetalleHorario: event.id,
                                horaEntrada: event.start,
                                horaSalida: event.end,
                                idPeriodo: idPeriodo,
                                nombre: event.title,
                                detalle: idDistribucion,
                                backgroundColor: "<%Response.Write(Request.QueryString["ca"].ToString()); %>"
                            };
                            PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
                        }
                        else {
                        
                            error('Solo intervalos de una hora, por favor verifique.');
                            revertFunc();
                        }
                    }
                    
                }, 
                droppable: true, // this allows things to be dropped onto the calendar !!!
                eventDrop: function (event,dayDelta,minuteDelta,allDay,revertFunc) {

                    if (event.id == 'CASYS') {
                        revertFunc();
                    }
                    else {
                        var eventToUpdate = {
                            idDetalleHorario: event.id,
                            horaEntrada: event.start,
                            horaSalida: event.end,
                        }
                        PageMethods.UpdateEventDrop(eventToUpdate, updateSuccess);
                    }
                   
                },
                drop: function (date, allDay) { // this function is called when something is dropped
                    // retrieve the dropped element's stored Event Object
                    var originalEventObject = $(this).data('eventObject');
                    // we need to copy it, so that multiple events don't have a reference to the same object
                    var copiedEventObject = $.extend({}, originalEventObject);
                    // assign it the date that was reported
                    copiedEventObject.start = date;
                    copiedEventObject.allDay = false;
                    copiedEventObject.backgroundColor = $(this).css("background-color");
                    copiedEventObject.borderColor = $(this).css("border-color");
                    // render the event on the calendar
                    // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)

                    var idPeriodo = "<%Response.Write(Session["periodo"].ToString()); %>";
                    var idDetalleHorario = "<%Response.Write(Session["idDocente"].ToString()); %>";
                    var eventToAdd = {
                        id: copiedEventObject.id,
                        horaEntrada: copiedEventObject.start,
                        horaSalida: copiedEventObject.start,
                        backgroundColor: rgb2hex(copiedEventObject.backgroundColor),
                        borderColor: rgb2hex(copiedEventObject.backgroundColor),
                        idPeriodo: idPeriodo,
                        nombre: copiedEventObject.title,
                        idDetalleHorario: idDetalleHorario,
                        detalle: "<%Response.Write(Request.QueryString["ca"].ToString()); %>"
                    };
                    PageMethods.addEventHora(eventToAdd, addSuccess);
                    $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
                }

                <%  }
            else
            {  %> 
                    
                editable: false,
            selectable: false,
            droppable: false, // this allows things to be dropped onto the calendar !!!
          <%      
            }
        }
        else
        {
             %>
            editable: false,
            selectable: false,
            droppable: false, // this allows things to be dropped onto the calendar !!!
                <%
        }
        %>
            });
        });
    </script>
</asp:Content>
